using System;
using MySql.Data.MySqlClient; // 改用MySQL客户端
using System.Windows;
using System.Windows.Forms;
using MessageBox = System.Windows.MessageBox;
using System.Windows.Input;

using System.IO;

using System.Linq;
using System.Collections.Generic;


namespace MainUI
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            HotkeyManager.Initialize(this);
            Loaded += OnLoaded;
            Closed += OnClosed;
        }

        private void SetSavePicPosButton_Click(object sender, RoutedEventArgs e)
        {
            using (var folderBrowser = new FolderBrowserDialog())
            {
                folderBrowser.Description = "请选择用于存储文件的文件夹";
                var result = folderBrowser.ShowDialog();

                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    SavePicBox.Text = folderBrowser.SelectedPath;
                }
                else
                {
                    MessageBox.Show(
                        "未选择任何文件夹",
                        "提示",
                        MessageBoxButton.OK,
                        MessageBoxImage.Warning
                    );
                }
            }

            // MySQL连接字符串,注意要连接到你的数据库
            const string connectionString = "Server=localhost;Port=3306;Database=screenpic;Uid=root;Pwd=你的密码;";

            // 修正后的MySQL建表语句
            const string createTableSql = @"
CREATE TABLE IF NOT EXISTS screenshots (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,  -- MySQL使用AUTO_INCREMENT
    file_name VARCHAR(255) NOT NULL,
    file_path VARCHAR(512) NOT NULL,
    file_format VARCHAR(20) NOT NULL,
    capture_width INT NOT NULL,
    capture_height INT NOT NULL,
    capture_area VARCHAR(50),
    create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,  -- MySQL使用CURRENT_TIMESTAMP
    last_modify_time DATETIME,
    is_deleted TINYINT NOT NULL DEFAULT 0,
    parent_screenshot BIGINT,
    FOREIGN KEY (parent_screenshot) REFERENCES screenshots(id)
) ENGINE=InnoDB;";  // 明确指定存储引擎

            try
            {
                using (var connection = new MySqlConnection(connectionString)) // 使用MySqlConnection
                {
                    connection.Open();
                    using (var command = new MySqlCommand(createTableSql, connection))
                    {
                        command.ExecuteNonQuery();
                    }
                }
                MessageBox.Show("数据库连接成功，表结构初始化完成", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"数据库操作失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ViewPicButton_Click(object sender, RoutedEventArgs e)
        {
            // 检查是否已选择存储路径
            if (string.IsNullOrWhiteSpace(SavePicBox.Text))
            {
                MessageBox.Show("请先选择图片存储路径", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // 生成HTML文件路径（保存到用户选择的目录）
            string htmlPath = System.IO.Path.Combine(SavePicBox.Text, "screenshot_viewer.html");

            try
            {
                // 从数据库获取元数据
                var metaData = new List<Dictionary<string, object>>();
                const string connectionString = "Server=localhost;Port=3306;Database=screenpic;Uid=root;Pwd=hjj1019583787;";

                using (var connection = new MySqlConnection(connectionString))
                {
                    connection.Open();
                    const string query = "SELECT id, file_name, file_path, file_format, create_time FROM screenshots";

                    using (var command = new MySqlCommand(query, connection))
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var record = new Dictionary<string, object>();
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                record[reader.GetName(i)] = reader.GetValue(i);
                            }
                            metaData.Add(record);
                        }
                    }
                }

                // 生成HTML内容
                var html = new System.Text.StringBuilder();
                html.AppendLine("<!DOCTYPE html>");
                html.AppendLine("<html><head>");
                html.AppendLine("<meta charset='UTF-8'>");
                html.AppendLine("<title>截图查看器</title>");
                html.AppendLine("<style>");
                html.AppendLine("body { font-family: Arial, sans-serif; margin: 20px; }");
                html.AppendLine(".item { border: 1px solid #ddd; padding: 15px; margin-bottom: 20px; }");
                html.AppendLine("img { max-width: 300px; height: auto; }");
                html.AppendLine("</style></head><body>");
                html.AppendLine("<h1>截图列表</h1>");

                // 遍历元数据
                foreach (var item in metaData)
                {
                    string fileName = item["file_name"].ToString();
                    string filePath = System.IO.Path.Combine(SavePicBox.Text, fileName);

                    html.AppendLine("<div class='item'>");
                    html.AppendLine($"<h3>{System.Web.HttpUtility.HtmlEncode(fileName)}</h3>");
                    html.AppendLine($"<p>创建时间：{item["create_time"]}</p>");
                    html.AppendLine($"<p>文件格式：{item["file_format"]}</p>");

                    // 显示图片（检查文件是否存在）
                    if (System.IO.File.Exists(filePath))
                    {
                        html.AppendLine($"<img src='file:///{filePath.Replace(@"\", "/")}' alt='{System.Web.HttpUtility.HtmlEncode(fileName)}'/>");
                    }
                    else
                    {
                        html.AppendLine("<p style='color: red;'>图片文件不存在</p>");
                    }

                    html.AppendLine("</div>");
                }

                html.AppendLine("</body></html>");

                // 写入HTML文件
                System.IO.File.WriteAllText(htmlPath, html.ToString());

                // 提示用户文件位置
                MessageBox.Show(
                    $"查看文件已生成至：\n{htmlPath}",
                    "生成成功",
                    MessageBoxButton.OK,
                    MessageBoxImage.Information
                );

                // 自动定位文件（可选）
                System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{htmlPath}\"");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成查看页面失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    



    private int _fixedHotkeyId = -1;
        private int _customHotkeyId = -1;


        private void SetPRSCButton_Click(object sender, RoutedEventArgs e)
        {
            var settingsWindow = new HotkeySettingsWindow();
            if (settingsWindow.ShowDialog() == true)
            {
                RegisterHotkeys();
            }
        }
        private void RegisterHotkeys()
        {
            if (!string.IsNullOrEmpty(Properties.Settings.Default.FixedHotkey))
            {
                var (fixedMod, fixedKey) = ParseHotkey(Properties.Settings.Default.FixedHotkey);
                _fixedHotkeyId = HotkeyManager.Register(fixedMod, fixedKey, CaptureFixedScreenshot);
            }

            if (!string.IsNullOrEmpty(Properties.Settings.Default.CustomHotkey))
            {
                var (customMod, customKey) = ParseHotkey(Properties.Settings.Default.CustomHotkey);
                _customHotkeyId = HotkeyManager.Register(customMod, customKey, CaptureCustomScreenshot);
            }
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
            {
                // 注册热键
                try
                {
                    var (fixedMod, fixedKey) = ParseHotkey(Properties.Settings.Default.FixedHotkey);
                    _fixedHotkeyId = HotkeyManager.Register(fixedMod, fixedKey, CaptureFixedScreenshot);

                    var (customMod, customKey) = ParseHotkey(Properties.Settings.Default.CustomHotkey);
                    _customHotkeyId = HotkeyManager.Register(customMod, customKey, CaptureCustomScreenshot);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "热键初始化失败", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            private void OnClosed(object sender, EventArgs e)
            {
                // 注销热键
                if (_fixedHotkeyId != -1) HotkeyManager.Unregister(_fixedHotkeyId);
                if (_customHotkeyId != -1) HotkeyManager.Unregister(_customHotkeyId);
            }

            private (ModifierKeys modifiers, Key key) ParseHotkey(string hotkey)
            {
                if (string.IsNullOrEmpty(hotkey)) throw new ArgumentException("空快捷键配置");

                var parts = hotkey.Split(new[] { "+" }, StringSplitOptions.RemoveEmptyEntries)
                                 .Select(p => p.Trim())
                                 .ToArray();

                ModifierKeys mods = ModifierKeys.None;
                Key finalKey = Key.None;

                foreach (var part in parts.Take(parts.Length - 1))
                {
                    switch (part.ToUpper())
                    {
                        case "CTRL": mods |= ModifierKeys.Control; break;
                        case "ALT": mods |= ModifierKeys.Alt; break;
                        case "SHIFT": mods |= ModifierKeys.Shift; break;
                        case "WIN": mods |= ModifierKeys.Windows; break;
                        default: throw new FormatException($"无效的修饰键: {part}");
                    }
                }

                if (!Enum.TryParse(parts.Last(), true, out finalKey))
                {
                    throw new FormatException($"无效的按键: {parts.Last()}");
                }

                return (mods, finalKey);
            }

            private void CaptureFixedScreenshot()
            {
                try
                {
                    var size = Properties.Settings.Default.AreaSize.Split(',')
                        .Select(int.Parse).ToArray();

                    if (size.Length != 2) throw new InvalidOperationException("无效的截图尺寸配置");

                    // 实现固定区域截图
                    var screen = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
                    using (var bitmap = new System.Drawing.Bitmap(size[0], size[1]))
                    using (var graphics = System.Drawing.Graphics.FromImage(bitmap))
                    {
                        graphics.CopyFromScreen(
                            screen.Width / 2 - size[0] / 2,
                            screen.Height / 2 - size[1] / 2,
                            0, 0,
                            new System.Drawing.Size(size[0], size[1])
                        );

                        SaveScreenshot(bitmap);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"固定截图失败: {ex.Message}", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            private void CaptureCustomScreenshot()
            {
                try
                {
                    // 实现拖拽区域截图
                    var regionSelector = new RegionSelectorWindow();
                    if (regionSelector.ShowDialog() == true)
                    {
                        var rect = regionSelector.SelectedRegion;
                        using (var bitmap = new System.Drawing.Bitmap((int)rect.Width, (int)rect.Height))
                        using (var graphics = System.Drawing.Graphics.FromImage(bitmap))
                        {
                            graphics.CopyFromScreen(
                                (int)rect.Left,
                                (int)rect.Top,
                                0, 0,
                                new System.Drawing.Size((int)rect.Width, (int)rect.Height)
                            );

                            SaveScreenshot(bitmap);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"区域截图失败: {ex.Message}", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            private void SaveScreenshot(System.Drawing.Bitmap bitmap)
            {
                var savePath = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
                    $"Screenshot_{DateTime.Now:yyyyMMddHHmmss}.png"
                );

                bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Png);
                MessageBox.Show($"截图已保存至: {savePath}", "完成",
                    MessageBoxButton.OK, MessageBoxImage.Information);
            }
    }
}